package com.piik.mall.product.service.impl;

import com.piik.common.constant.ProductConstant;
import com.piik.mall.product.dao.AttrAttrgroupRelationDao;
import com.piik.mall.product.dao.AttrGroupDao;
import com.piik.mall.product.entity.AttrAttrgroupRelationEntity;
import com.piik.mall.product.entity.AttrGroupEntity;
import com.piik.mall.product.entity.CategoryEntity;
import com.piik.mall.product.service.AttrAttrgroupRelationService;
import com.piik.mall.product.service.AttrGroupService;
import com.piik.mall.product.service.CategoryService;
import com.piik.mall.product.vo.AttrResponseVO;
import com.piik.mall.product.vo.AttrVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.piik.common.utils.PageUtils;
import com.piik.common.utils.Query;

import com.piik.mall.product.dao.AttrDao;
import com.piik.mall.product.entity.AttrEntity;
import com.piik.mall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> list = attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id",attrgroupId));
        List<AttrEntity> attrEntities = list.stream().map(
                (entity) -> this.getById(entity.getAttrId()))
                .filter((entity) -> entity != null)
                .collect(Collectors.toList());
        return attrEntities;
    }

    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {

        // 1.查询当前属性组所在的类别编号,获取对应分类Id
        AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();

        // 2.当前属性组只能关联自己所属的分类下其他没有关联的属性信息
        // 2.1 先查找这个分类下所有分组信息
        List<AttrGroupEntity> attrGroupEntities= attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id",catelogId));
        // 2.2 获取属性组所有集合
        List<Long> groupIds =attrGroupEntities.stream().map((entity)->entity.getAttrGroupId()).collect(Collectors.toList());
        // 2.3 查询当前分类的所有属性组已经分配的属性信息
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIds));
        List<Long> attrIds = attrAttrgroupRelationEntities.stream().map((entity)->entity.getAttrId()).collect(Collectors.toList());
        // 2.4 根据分类所有属性组的属性信息排除已经分配的信息,得到未分配的属性信息

        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id",catelogId)
                .eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());

        // 2.5 添加排除条件
        if(attrIds != null && attrIds.size()>0){
            wrapper.notIn("attr_id",attrIds);
        }

        // 2.6 根据key查询
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper);

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, String attrType, Long catelogId) {
        QueryWrapper<AttrEntity> wrapper= new QueryWrapper<>();

        // 查询基本属性
        wrapper.eq("attr_type","base".equalsIgnoreCase(attrType)?1:0);
        // 1.根据分类编码查询
        if(catelogId !=0){
            wrapper.eq("catelog_id",catelogId);
        }

        // 2.根据key模糊查询
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((obj)->{
                obj.eq("attr_id",key).or().like("attr_name",key);
            });
        }

        // 3.分页查询
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params),wrapper);

        PageUtils pageUtils = new PageUtils(page);

       List<AttrEntity> attrEntities = page.getRecords();
        List<AttrResponseVO> list = attrEntities.stream().map((attrEntity) -> {
            AttrResponseVO attrResponseVO = new AttrResponseVO();
            // 拷贝属性值到返回值对象中
            BeanUtils.copyProperties(attrEntity, attrResponseVO);
            // 查询分类名称,并添加到返回值对象中
            CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrResponseVO.setCatelogName(categoryEntity.getName());
            }

            //基本属性
            if ("base".equalsIgnoreCase(attrType)) {
                // 设置属性组的名称
                AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
                // 去关联表中找到对应的属性组ID
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao
                        .selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if (attrAttrgroupRelationEntity != null && attrAttrgroupRelationEntity.getAttrGroupId() != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrAttrgroupRelationEntity.getAttrGroupId());
                    if (attrGroupEntity != null) {
                        attrResponseVO.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
            }
            return attrResponseVO;
        }).collect(Collectors.toList());
        pageUtils.setList(list);
        return pageUtils;
    }


    @Override
    @Transactional
    public void save(AttrVO vo) {
        //1.保存规格参数的基本信息
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(vo,attrEntity);
        this.save(attrEntity);

        //2.保存规格参数对应的属性组关联信息
        if(vo.getAttrGroupId()!=null ){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity= new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(vo.getAttrGroupId());
            attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);

        }
    }

    @Override
    public AttrResponseVO getAttrInfo(Long attrId) {

        // 1. 声明返回对象
        AttrResponseVO attrResponseVO = new AttrResponseVO();

        // 2. 查询规格参数基本信息
        AttrEntity attrEntity= this.getById(attrId);
        BeanUtils.copyProperties(attrEntity,attrResponseVO);

        // 3. 查询关联信息中属性组id
        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){

            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao
                    .selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrEntity.getAttrId()));
            if(relationEntity != null){
                AttrGroupEntity attrGroupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
                attrResponseVO.setAttrGroupId(attrGroupEntity.getAttrGroupId());
                if(attrGroupEntity != null ){
                    attrResponseVO.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }
        // 4. 查询关联分类信息
        Long catelogId= attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        attrResponseVO.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryService.getById(catelogId);
        if(categoryEntity != null){
            attrResponseVO.setCatelogName(categoryEntity.getName());
        }
        return attrResponseVO;
    }

    @Transactional
    @Override
    public void updateBaseAttr(AttrVO vo) {

      // 1. 更改规格参数基本信息
      AttrEntity entity = new AttrEntity();
      BeanUtils.copyProperties(vo,entity);
      this.updateById(entity);

      // 2. 修改分组关联的关系
      if(entity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){

          AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
          relationEntity.setAttrId(entity.getAttrId());
          relationEntity.setAttrGroupId(vo.getAttrGroupId());
          // 2.1 判断是否存在对应的数据
          Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",vo.getAttrId()));
          if(count>0){
              // 2.2 有记录更新
              attrAttrgroupRelationDao.update(relationEntity,new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",vo.getAttrId()));
          }else {
              // 2.3 没有记录插入
              attrAttrgroupRelationDao.insert(relationEntity);
          }
      }
    }

    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        List<Long> collect = null ;
        if(attrIds != null && attrIds.size()>0){

            List<AttrEntity>  list = this.list(new QueryWrapper<AttrEntity>().
                    in("attr_id", attrIds).eq("search_type", 1));

            if(list != null && list.size()>0){

                collect = list.stream().map(item -> {
                    return item.getAttrId();
                }).collect(Collectors.toList());

            }
        }
        return collect;
    }


}